package com.yunfinal.api.service.doc;

import com.alibaba.fastjson.JSONObject;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 参数文档对象生成
 *
 * @author 杜福忠 2019-03-08 18:20:33
 */
public class ApiDocData extends JSONObject {

    protected JSONObject dataDoc;
    protected String paraStr;

    public ApiDocData() {
        super(true);
    }

    public ApiDocData put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    /**
     * 加入参数
     *
     * @param key   参数名
     * @param value 参数值
     * @param doc   解释说明
     * @return
     */
    public ApiDocData put(String key, Object value, String doc) {
        put(key, value);
        dataDocPut(key, value, doc, false);
        return this;
    }

    protected void dataDocPut(String key, Object value, String doc, boolean notNull) {
        dataDoc().put(key, new ApiDocDataPara(key, notNull, findTypeName(value), doc, value));
    }

    /**
     * 加入参数（文档中会标识为“必填项”）
     *
     * @param key   参数名
     * @param value 参数值
     * @param doc   解释说明
     * @return
     */
    public ApiDocData putMust(String key, Object value, String doc) {
        put(key, value);
        dataDocPut(key, value, doc, true);
        return this;
    }

    protected String findTypeName(Object value) {
        String typeName = "对象";
        if (value instanceof CharSequence) {
            typeName = "字符串";
        } else if (value instanceof Number) {
            typeName = "数字";
        } else if (value instanceof Date) {
            typeName = "日期";
        } else if (value instanceof List || value instanceof Object[]) {
            typeName = "数组";
        } else if (value instanceof Map) {
            typeName = "键值";
        }
        return typeName;
    }

    public JSONObject dataDoc() {
        if (null == dataDoc) {
            dataDoc = new JSONObject(true);
        }
        return dataDoc;
    }

    public boolean existDataDoc() {
        return null != dataDoc;
    }

    public ApiDocDataPara dataDocGet(String key) {
        return (ApiDocDataPara) dataDoc().get(key);
    }

    public String paraStr() {
        return paraStr;
    }

    public void paraStr(String paraStr) {
        this.paraStr = paraStr;
    }

    @Override
    public String toString() {
        return "ApiDocData{" +
                "dataDoc=" + dataDoc.toJSONString() +
                "data=" + super.toJSONString() +
                '}';
    }
}
